package org.nutz.jst.loader.impl;

import java.io.InputStream;

import org.nutz.jst.impl.JstImpl;
import org.nutz.jst.loader.JstLoader;
import org.nutz.lang.Streams;

public class JstClasspathLoader extends JstLoader {

    protected ClassLoader classLoader;

    public JstClasspathLoader() {
        classLoader = getClass().getClassLoader();
    }

    public void setClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    public boolean has(String key) {
        return classLoader.getResource(root + key) != null;
    }

    public JstImpl get(String key) {
        InputStream ins = classLoader.getResourceAsStream(root + key);
        if (ins == null)
            return null;
        byte[] buf = Streams.readBytesAndClose(ins);
        return build(buf);
    }

    public String forPrint() {
        return "classpath(root=" + root + ")";
    }

}
